<?php
// TODO Date of birth validation
class EmbeddedParticipantValidatorSchema extends sfValidatorSchema
{
  const OPTION_ALLOW_EMPTY = 'allow_empty';
  const OPTION_LOGGER = 'logger';

  protected function configure ($options = array(), $messages = array())
  {
    $this->addOption(self::OPTION_ALLOW_EMPTY, false);
    $this->addOption(self::OPTION_LOGGER, null);
  }
  
  public function getLogger()
  {
    return $this->getOption(self::OPTION_LOGGER);
  }

  protected function doClean ($values)
  {    
    $this->getLogger()->debug(sprintf('Calling %s', __METHOD__));
    $empty_forms = 0;
    $allow_empty_forms = $this->getOption(self::OPTION_ALLOW_EMPTY);
    $this->getLogger()->debug(sprintf('Allow empty forms: %s', ($allow_empty_forms ? 'TRUE' : 'FALSE')));
    
    $errorSchema = new sfValidatorErrorSchema($this);
    $defaultMessages = array('required' => 'Pflichtfeld', 'invalid' => 'Ungültig');
    $validatorSchema = array(
      'first_name' => new sfValidatorString(array('max_length' => 255), $defaultMessages),
      'last_name'     => new sfValidatorString(array('max_length' => 255), $defaultMessages),
      'gender'        => new sfValidatorChoice(array('choices' => array(0 => 'm', 1 => 'f'), 'required' => true), $defaultMessages),
      'date_of_birth' => new sfValidatorString(array('required' => true), $defaultMessages),
//      'date_of_birth' => new sfValidatorDate(array('required' => true, 'date_format' => '~(?P<day>\d{2})\.(?P<month>\d{2})\.(?P<year>\d{4})~'), array_merge($defaultMessages, array('bad_format' => 'Ungültig'))),
//      'date_of_birth' => new sfValidatorRegex(array('pattern' => '~(\d{2})\.(\d{2})\.(\d{4})~'), $defaultMessages),
      'vegetarian'    => new sfValidatorBoolean(array('required' => true), $defaultMessages),
      'chapter'       => new sfValidatorString(array('max_length' => 255, 'required' => true), $defaultMessages),
      'age_group'     => new sfValidatorChoice(array('choices' => array(0 => 'b', 1 => 'w', 2 => 'p', 3 => 'r', 4 => 'm'), 'required' => true), $defaultMessages),
      'accomodation'  => new sfValidatorChoice(array('choices' => array(0 => 't', 1 => 'h'), 'required' => true), array('required' => 'Pflichtfeld', 'invalid' => 'Ungültig'))
    );
    
    $this->getLogger()->debug(sprintf('Iterating over %s fields', count($values)));
    foreach ($values as $key => $value)
    {
      
      $localErrorSchema = new sfValidatorErrorSchema($this);
      
      if (! $value['first_name'] && ! $value['last_name']) // TODO Enough parameters to determine 'empty' participants?
      {
        $this->getLogger()->debug(sprintf('First and last name are not set for index %s', $key));
        if ($allow_empty_forms == false || $empty_forms >= $allow_empty_forms)
        {
          $this->getLogger()->debug('Unsetting values');
          unset($values[$key]);
        }
        else
        {
          $empty_forms ++;
          unset($values[$key]);
          $this->getLogger()->debug(sprintf('Incremented $empty_forms, now %s', $empty_forms));
        }
      }
      else
      {
        if(is_array($value)) {
          foreach($value as $field => $field_value) {
            try {
              if(isset($validatorSchema[$field])) {
                $validatorSchema[$field]->clean($field_value);
              }
            } catch(sfValidatorError $error) {
              $localErrorSchema->addError($error, $field);
            }
          }
        }
//        if (! $value['first_name'])
//        {
//          $localErrorSchema->addError(new sfValidatorError($this, 'required'), 'first_name');
//        }
//        if (! $value['last_name'])
//        {
//          $localErrorSchema->addError(new sfValidatorError($this, 'required'), 'last_name');
//        }
//        if (! $value['date_of_birth'])
//        {
//          $localErrorSchema->addError(new sfValidatorError($this, 'required'), 'last_name');
//        }
      }
      
      if (count($localErrorSchema))
      {
        $errorSchema->addError($localErrorSchema, (string) $key);
      }
    }
    
    if (count($errorSchema))
    {
      throw new sfValidatorErrorSchema($this, $errorSchema);
    }
    
    return $values;
  }
}